package com.zt.student.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.zt.common.common.CodeMsg;
import com.zt.common.pojo.ActiveClass;
import com.zt.common.pojo.StudentVx;
import com.zt.common.pojo.common.JsonResult;
import com.zt.common.pojo.netty.Sender;
import com.zt.common.pojo.origin.OriginStudent;
import com.zt.common.utils.JwtUtil;
import com.zt.common.utils.RedisUtil;
import com.zt.common.utils.UserUtil;
import com.zt.student.dto.StudentDTO;
import com.zt.student.service.OriginStudentService;
import com.zt.student.service.impl.StudentServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * description:
 * author:zt
 * date:2021-11-25
 */
@RestController
@RequestMapping("student")
@CrossOrigin
@Api("用户模块")
public class StudentController {

    @Autowired
    private StudentServiceImpl studentService;
    @Autowired
    private OriginStudentService originStudentService;
    @Autowired
    private RedisUtil redisUtil;


    @GetMapping("hello")
    @ApiOperation("测试用的 你别管")
    public JsonResult<String> hello() {
//        redisUtil.set("2021-2022-2-hasSelectClass","2022-01-09 16:01:00");
//        Date time = new Date(System.currentTimeMillis() + (long)7* 24 * 60 * 60 * 1000);
//        String expireTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time);
//
//        redisUtil.set("2021-2022-2-hasSelectClass",expireTime);
//        redisUtil.set("2021-2022-2-selectClass",1, (long)7* 24 * 60 * 60);
        return JsonResult.success("ok");
    }

    @PostMapping("/login")
    @ApiOperation("登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "小程序获取的code"),
            @ApiImplicitParam(name = "rawData", value = "用户非敏感信息"),
            @ApiImplicitParam(name = "signature", value = "签名")
    })
    public JsonResult<String> login(@RequestParam(name = "code") String code,
                                    @RequestParam(name = "rawData") String rawData,
                                    @RequestParam(name = "signature") String signature,
                                    HttpServletRequest request, HttpServletResponse response){

        StudentVx student = studentService.handleLogin(code, rawData, signature, request);

        //未绑定学号
        if (null == student.getStudentId()) {
            //返回重定向信息，表示需要绑定用户信息
            // 则随机生成一个key关联该openId 用于学生关联studentId学生信息后再生成token
            String random = RandomUtil.randomString(8);
            redisUtil.set(random,student.getOpenId());
            return JsonResult.error(CodeMsg.REDIRECT,random);
        }else {
            //token在请求头
            String token = JwtUtil.getToken(student.getStudentId(), String.valueOf(System.currentTimeMillis()),0);
            response.setHeader("Authorization", token);
            response.setHeader("access-Control-Expose-Headers", "Authorization");

            OriginStudent originStudent = originStudentService.getOriginStuById(student.getStudentId());

            return JsonResult.success(JSON.toJSONString(new Sender(student.getStudentId(),originStudent.getStudentName(),student.getAvatar())));
        }

    }

    @PostMapping("update")
    @ApiOperation("更新用户信息绑定originStudentId")
    public JsonResult<String> update(@RequestBody StudentDTO studentDTO,HttpServletResponse response){
        String userInfo = studentService.update(studentDTO,response);

        return JsonResult.success(userInfo);
    }

    @GetMapping("check")
    @ApiOperation("检查token状态")
    public JsonResult check(HttpServletRequest request){
        if (UserUtil.checkUserStatus(request)) {
            return JsonResult.success();
        }
        else return JsonResult.error(CodeMsg.VERIFY_ERROR);
    }

    @GetMapping("getTime")
    @ApiOperation("获取当前日期")
    public JsonResult<String> getTime(){
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        return JsonResult.success(time);
    }

    @PostMapping("logOut")
    @ApiOperation("退出登录")
    public JsonResult logOut(HttpServletRequest request){
        studentService.logOut(request);
        return JsonResult.success();
    }

    @PostMapping("cancelBind")
    @ApiOperation("解除绑定学籍信息")
    public JsonResult cancelBindStuId(HttpServletRequest request){
        studentService.cancelBindStuId(request);
        return JsonResult.success();
    }

    @PostMapping("updateAvatar")
    @ApiOperation("上传头像")
    public JsonResult<String> updateAvatar(MultipartFile file,HttpServletRequest request) throws IOException {
        String avatarUrl = studentService.updateAvatar(file, request);
        return JsonResult.success(avatarUrl);
    }

}
